from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
from SeleniumTest.common import HttpTestLog
from SeleniumTest.common import userDefineException

def GetElement(by=By.ID,value="",driver=None):
    '''
    :param by: 搜索方式：id/xpath/name等
    :param value: 搜索特征值
    :return: 返回搜索到的第一个元素（此frame下的），如果没有搜索到元素返回None
    '''

    try:
        elm = driver.find_element(by=by, value=value)
        return elm
    except Exception as err:
        return None

def GetElements(by=By.ID,value="",driver=None):
    '''
    :param by: 搜索方式：id/xpath/name等
    :param value: 搜索特征值
    :return: 返回搜索到的所有元素（此frame下的），如果没有搜索到元素返回None
    '''
    elm = driver.find_elements(by=by, value=value)
    if elm != []:
        return elm
    else:
        return None

def searchElenmet(by=By.ID,inner_value="",driver=None):
    '''
    全局搜索页面特征元素，返回最先找到的页面(frame)下的元素，一个、多个、none#迭代查找
    :param by: 搜索方式：id/xpath/name等
    :param value: 搜索特征值
    :return:返回最先找到的页面(frame)下的元素，一个、多个、none//还未完全验证，在同级第二个frame下能否找到元素
    '''
    elms = GetElements(by=by,value=inner_value,driver=driver)
    if elms :
        if len(elms)>1:
            print("more than one element find in this frame, return first element")#返回元素有可能大于一个加入提示
        return elms[0]#返回第一个元素
    elif elms == None:
        frames = GetElements(by=By.XPATH, value=r"//iframe",driver=driver)
        # print(frames)
        if frames:
            for frame in frames:
                # print(frame)#打印frame
                driver.switch_to.frame(frame)
                elms = searchElenmet(by=by,inner_value=inner_value,driver=driver)
                if elms:
                    return elms
                elif elms == None:
                    driver.switch_to.parent_frame()
        else:
            # driver.switch_to.parent_frame()
            return None


class seleTest():
    def __init__(self):
        self.testLog = HttpTestLog.Log.get_log(__name__)
        self.testErr = userDefineException.userDefineError
        self.actType = ["click","select","sendkey"]
        self.testDriver = webdriver.Chrome()

    def open_url(self,url):
        try:
            self.testDriver.get(url)
        except(SystemExit, KeyboardInterrupt):
            raise
        except Exception as err:
            self.testLog.error("something wrong!", exc_info=True)

    def findElement(self,search_type,inner_propert=None):
        elm = searchElenmet(by=search_type,inner_value=inner_propert,driver=self.testDriver)
        if elm:
            return elm
        else:
            err = self.testErr(message="can not find element")
            self.testLog.error(err)

    def elementClick(self,element):
        # self.ieDriver.find_element_by_id(id).click()
        element.click()
        # time.sleep(3)

    def elementSendKey(self,element,value):
        # self.ieDriver.find_element_by_id(id).send_keys(value)
        element.send_keys(value)
        # time.sleep(3)

    def elementSelect(self,element,value):
        # Select(self.ieDriver.find_element_by_id(id)).select_by_value(value)
        Select(element).select_by_value(value)
        # time.sleep(3)

    def actJudge(self,act):
        if act not in self.actType:
            exception = self.testErr(message="can not invoke this action : %s" %act)
            self.testLog.error(exception)

    def elementAct(self,search_type=None,inner_propert=None,act_name="",value="",name=""):
        self.actJudge(act_name)
        self.testLog.info("对 “%s（%s）”进行“%s”操作" % (name,inner_propert,act_name))
        element = self.findElement(search_type=search_type,inner_propert=inner_propert)

        if act_name == "click":
            self.elementClick(element)
        elif act_name == "sendkey":
            self.elementSendKey(element, value)
        elif act_name == "select":
            self.elementSelect(element, value)

# if __name__ == '__main__':
#     driver = webdriver.Ie()
#     driver.get("http://192.168.65.166/Index.html#")
#     searchElenmet(by=By.ID, inner_value=r"departmentSelect", driver=driver).click()
#     Select(driver.find_element_by_id("userName")).select_by_index(2)
#     ele = searchElenmet(by=By.ID,inner_value=r"userName",driver=driver)
#     Select(ele).select_by_value("变电3")
#     print(dir(searchElenmet(by=By.ID,inner_value=r"userName",driver=driver)))
#     if driver.find_element_by_id("userName") == searchElenmet(by=By.ID,inner_value=r"userName",driver=driver):
#         print(1)
#     else:
#         print(0)
#     Select(driver.find_element_by_id("userName")).select_by_value("变电2")
#     time.sleep(2)
#     driver.find_element(by=By.ID,value="bt_Login").click()
#     time.sleep(2)
#     driver.find_element(by=By.ID,value="bt_GZPDBTaskForm").click()
#     time.sleep(2)
#     # Select(self.ieDriver.find_element_by_xpath(r"//%s[@id='%s']" % (div, id))).select_by_value(value)
#     elm = searchElenmet(by=By.ID,inner_value=r"TextBox_Data4_20160817085213",driver=driver)
#     if elm:
#         elm.send_keys("asdasf")
#     else:
#         print("none")
#
#     # driver.close()